import React, { Component } from 'react'
import { Button, Drawer, Alert, Badge, Divider, Upload, Icon, Row, Modal } from 'antd';
import '@/assets/css/settings';
import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout';
import { BasicPagination, TableCustomize, compareNum, openSuccessModal, openModalMessage } from '../../../components/TableCustomize'
import { Link } from 'react-router-dom';
import SearchForm from './SearchForm';
import AddForm from './AddForm';
import * as APIService from '../../../axios/api_yq'
import { baseUrl, toLead } from '../../../config'
import { withPermission } from '../../../components/withpermission'
const CreateButton = withPermission(Button, 'plus')
const DeleteButton = withPermission(Button, 'line')
const PrintButton = withPermission(Button, 'printer')
const DownLoadButton = withPermission(Button, 'download')
const UploadButton = withPermission(Button, 'upload')
const { confirm } = Modal;
export default class InspectionStandard extends Component {
	state = {
		dataSource: [
		],
		formData: {},
		drawerVisible: false,
		drawerTitle: '新增',
		compile: {},
		columns: [
			{
				title: '序号',
				dataIndex: 'number',
				width: 50,
				align: 'center',
				render: (text, record, index) =>
					<div>
						{index + 1}
					</div>
			},
			{
				title: '表单编码',
				dataIndex: 'code',
				width: 130,
				// ellipsis: true,
				sorter: (a, b) => compareNum(a.code, b.code),
			},

			{
				title: '表单名称',
				width: 180,
				dataIndex: 'name',
				// ellipsis: true,
			},
			{
				title: '表单类型',
				width: 100,
				dataIndex: 'type',
				// ellipsis: true,
				sorter: (a, b) => compareNum(a.type, b.type),
				render: (text, record, index) =>
					<div>
						{
							text === '0' ? '试机' : text === '1' ? '自检' : text === '2' ? '质检' : null
						}
					</div>
			},
			{
				title: '适用对象',
				width: 150,
				dataIndex: 'object',
				// ellipsis: true,
			},
			{

				title: '备注',
				width: 150,
				dataIndex: 'remark',
				// ellipsis: true,
			},
			{

				title: '创建人',
				width: 100,
				dataIndex: 'creater',
				// ellipsis: true,
			},
			{

				title: '创建时间',
				width: 150,
				dataIndex: 'createTime',
				// ellipsis: true,
			},
			{

				title: '状态',
				width: 100,
				dataIndex: 'isDelete',
				// ellipsis: true,
				render: (text, record) =>
					record.isDelete === 1 ? <Badge status="error" text={'停用'} /> : <Badge status='success' text={'启用'} />
			},
			{
				title: '操作',
				dataIndex: 'opts',
				width: 230,
				render:
					(text, record) =>
						<div>
							<Link onClick={this.examine.bind(this, record)} to='/examineHave'>{'查看'}</Link>
							<Divider type="vertical" />
							<Link to='/shiftIns' onClick={this.compile.bind(this, record)}>{'编辑检验项'}</Link>
							<Divider type="vertical" />
							<a onClick={() => this.deleteRow1(record)}>{'删除'}</a>
							<Divider type="vertical" />
							{
								record.isDelete === 1 ? <a onClick={this.startUsing.bind(null, record)} >{'启用'}</a> : <a onClick={this.stop.bind(null, record)} >{'停用'}</a>
							}
						</div>
			},
			{ dataIndex: '' }
		],
		columns1: [
			{
				title: '序号',
				dataIndex: 'number',
				width: 50,
				align: 'center',
				render: (text, record, index) =>
					<div>
						{index + 1}
					</div>
			},
			{
				title: '表单编码',
				dataIndex: 'code',
				width: 100,
				// ellipsis: true,
			},

			{
				title: '表单名称',
				width: 100,
				dataIndex: 'name',
				// ellipsis: true,
			},
			{
				title: '表单类型',
				width: 100,
				dataIndex: 'type',
				// ellipsis: true,
			},
			{
				title: '适用对象',
				width: 100,
				dataIndex: 'object',
				// ellipsis: true,
			},
			{

				title: '备注',
				width: 100,
				dataIndex: 'remark',
				// ellipsis: true,
			},
			{

				title: '创建人',
				width: 80,
				dataIndex: 'creater',
				// ellipsis: true,
			},
			{

				title: '创建时间',
				width: 100,
				dataIndex: 'createTime',
				// ellipsis: true,
			},
			{

				title: '状态',
				width: 70,
				dataIndex: 'isDelete',
				// ellipsis: true,
				render: (text, record) =>
					record.isDelete === 1 ? <Badge status="error" text={'停用'} /> : <Badge status='success' text={'启用'} />
			},
		],
		some: null,
		selectedRows: [],
		advanced: false,
		paging: {},
		values: {},
		one: false,
		control: false,
		buttonList: [],
		buttonLoading: false,
		returnModel: []
	};
	// 挂载前
	UNSAFE_componentWillMount() {
		this.fetch();
	}
	//初始化加载数据
	fetch = (page = 1, size = 100) => {
		const { values } = this.state
		const buttonList = JSON.parse(localStorage.getItem('buttonList'))
		// console.log('这是按钮', buttonList);
		if (buttonList ? buttonList.length !== 0 : null) {
			this.setState({
				buttonList
			})
		}
		this.setState({
			loading: true,
			one: false,
			drawerVisible: false,
			formData: {},
			// 操作后清除选中
			selectedRowKeys: [],
			selectedRows: [],
			some: null,
			paging: { pageNum: page, pageSize: size }
		})
		let a = { pageNum: page, pageSize: size }
		setTimeout(() => {
			this.search({ ...values, ...a })
		}, 300);
	}
	// 查询接口
	search = (value, paging) => {
		APIService.queryQualityForm(value, paging).then((item) => {
			// console.log('查询数据', item);
			if (item.data.code === 200) {
				// openSuccessModal('查询成功')
				this.setState({
					loading: false,
					dataSource: item.data.data.data,
					// 操作后清除选中
					selectedRowKeys: [],
					selectedRows: [],
					some: null,
					paging: {
						pageNum: item.data.data.pageNum,
						pageSize: item.data.data.pageSize,
						total: item.data.data.total,
					}
				})
			} else {
				openModalMessage('error', item.data.msg)
			}
		})
	}
	// 新增接口/修改
	newData = (data) => {
		const { values, paging } = this.state
		APIService.addQualityForm(data).then((item) => {
			console.log(item);
			if (item.data.code === 200) {
				this.handleCancel()
				openSuccessModal(item.data.msg)
				this.search({ ...values, ...paging })
			} else {
				this.setState({
					buttonLoading: false
				})
				openModalMessage('error', item.data.msg)
			}
		})
	}
	// 删除接口
	deletes = (data) => {
		const { values, paging } = this.state
		APIService.deleteQualityForm(data).then((item) => {
			console.log(item);
			if (item.data.code === 200) {
				openSuccessModal(item.data.msg)
				this.search({ ...values, ...paging })
			} else {
				openModalMessage('error', item.data.msg)
			}
		})
	}
	// 查看
	examine = (a) => {
		sessionStorage.setItem('examineHave', JSON.stringify(a))
		console.log(a);
	}
	// 编辑检验项
	compile = (data) => {
		sessionStorage.setItem('compileCheckout1', JSON.stringify(data))
		console.log(data);
	}
	// 单条删除
	deleteRow1 = (b) => {
		const then = this
		let id = `idList=${[b.id]}`
		console.log('删除', id);
		confirm({
			title: '确认删除当项吗，这将影响其他数据模块?',
			onOk() {
				then.deletes(id)
			},
			onCancel() {
			},
		})
	}
	// 启
	startUsing = (data) => {
		this.newData({ ...data, isDelete: 0 })
	}
	// 停
	stop = (data) => {
		this.newData({ ...data, isDelete: 1 })
	}
	// 确定新增/修改
	onHandleOk = () => {
		this.formDrawer.validateFields((err, value) => {
			if (err) return;
			console.log(value.object, 'value.object');
			let objects = value.object.join('、')
			console.log(objects, 'objects');
			let data = { ...value, object: objects }
			this.setState({
				buttonLoading: true
			}, () => {
				this.newData(data)
			})
		})
	}
	// 取消
	handleCancel = e => {
		this.formDrawer && this.formDrawer.resetFields();
		this.setState({
			one: false,
			drawerVisible: false,
			formData: {},
			buttonLoading: false
		});
	};
	// 条件查询查询
	handleSearch = value => {
		const { paging, values } = this.state
		let a = { pageNum: paging.pageNum, pageSize: paging.pageSize }
		this.setState({
			values: value
		})
		console.log({ ...values, ...a });
		this.search({ ...value, ...a })
	};
	// loadData = (value, dataSource) => {
	// 	console.log('在表格行编辑后保存的数据', value, dataSource)
	// }
	//0新增  1修改
	create = () => {
		APIService.returnModel().then((value) => {
			console.log(value);
			let data = value.data.data
			this.setState({
				one: false,
				drawerVisible: true,
				returnModel: data,
				formData: {},
			});
		})

	};
	// 选中删除
	allStart = () => {
		const { selectedRows, some } = this.state
		let a = [...selectedRows]
		let ids = []
		a.forEach(item => {
			ids.push(item.id)
		})
		let id = `idList=${ids}`
		if (some !== null && some > 0) {
			this.deletes(id)
		} else {
			openModalMessage('error', '未选中')
		}

	}
	// 打印
	allStop = () => {
		// 创建html
		window.document.body.innerHTML = window.document.getElementById('prints').innerHTML;
		// 打印当前窗口内容
		window.print();
		// 刷新当前页面
		window.location.reload();
	}
	// 导出模板
	derive = () => {
		APIService.exportExcelDemo111().then(res => {
			console.log('这是什么', res);
			//设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
			let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
			// 创建A标签
			let link = document.createElement('a')
			link.style.display = 'none'
			link.href = url
			// 设置的下载文件文件名
			const fileName = decodeURI('质检表单');
			// 触发点击方法
			link.setAttribute('download', fileName)
			document.body.appendChild(link)
			link.click()
		})
	}
	// 导出选中
	derive2 = () => {
		const { selectedRows, some } = this.state
		if (some > 0 && some !== null && some !== 0) {
			APIService.exportExcel1(...selectedRows).then((res) => {
				//设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
				let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
				// 创建A标签
				let link = document.createElement('a')
				link.style.display = 'none'
				link.href = url
				// 设置的下载文件文件名
				const fileName = decodeURI('质检表单');
				// 触发点击方法25F45C1F.jpg
				link.setAttribute('download', fileName)
				document.body.appendChild(link)
				link.click()
			})
		} else {
			openModalMessage('error', '请选中导出项')
		}
	}
	// 重置
	cz = () => {
		this.setState({
			values: null
		}, () => { this.fetch() })
	}
	// 高级查询
	advancedss = () => {
		this.setState({ advanced: !this.state.advanced })
	}
	// 按钮点击事件
	// btnClick = (a) => {
	// 	if (a === 0) {
	// 		this.create()
	// 	}
	// 	if (a === 1) {
	// 		this.allStart()
	// 	}
	// 	if (a === 2) {
	// 		this.allStop()
	// 	}
	// 	if (a === 3) {
	// 		this.derive()
	// 	}
	// 	if (a === 4) {
	// 		this.derive2()
	// 	}
	// }
	componentWillUnmount() {
		this.setState = () => {
			return;
		};
	}
	render() {
		const then = this
		const { buttonLoading, buttonList, columns1, selectedRows, control, selectedRowKeys, advanced, some, loading, dataSource, formData, drawerVisible, drawerTitle, paging } = this.state
		const rowSelection = {
			columnWidth: '60px',
			type: 'radio',
			selectedRowKeys: selectedRowKeys,
			onChange: (selectedRowKeys, selectedRows) => {
				let some = [...selectedRows].length
				this.setState({
					some: some,
					selectedRows: selectedRows,
					selectedRowKeys: selectedRowKeys
				}, () => {
					console.log('选中个数', this.state.some, '选中详细数据', this.state.selectedRows);
				})
				if (some === 0 || some === null) {
					this.setState({
						control: false
					})
					return
				}
				this.setState({
					control: true
				})
			},
		}
		// 导入
		const propss = {
			name: 'file',
			action: `${baseUrl}${toLead}/qualityForm/importQualityFormExcel`,
			accept: '.xls,.xlsx',
			method: 'post',
			showUploadList: true,
			onRemove: true,
			headers: {
				userId: localStorage.getItem('userId'),
				Token: localStorage.getItem('token'),
			},
			onChange(info) {
				console.log('这是', info);
				if (info.file.status !== 'uploading') {
					console.log('这是什么', info.file, info.fileList);
				}
				if (info.file.status === 'done') {
					openSuccessModal('导入成功')
					then.fetch()

				} else if (info.file.status === 'error') {
					openModalMessage('error', '错误')
				}
			},
		}
		return (
			<div>
				<BasicLayoutSearch>
					<SearchForm onSearch={this.handleSearch}
						onClick={this.cz}
						onClick1={this.advancedss}
						advanced={advanced}
					/>
				</BasicLayoutSearch>
				{
					control === true ? <Alert message={<div>已选择 <span style={{ color: '#1890ff' }}>{some}</span> 项</div>} type="info" showIcon style={{ width: '99%', margin: 'auto' }} /> : null
				}
				<BasicLayout
					name="质检表单"
					icon="table"
					buttons={[
						<CreateButton key={1} onClick={this.create} icon="plus" />,
						<DeleteButton key={2} onClick={this.allStart} icon="delete" />,
						<PrintButton key={5} onClick={this.allStop} icon="printer" />,
						<DownLoadButton key={3} onClick={this.derive} icon="download" text="导出模板" />,
						<DownLoadButton key={4} onClick={this.derive2} icon="download" text="导出选中" />,
						<Upload {...propss} key={6}>
							<UploadButton icon="upload" />
						</Upload>,

						// <Button key={1} onClick={this.create} type="primary" icon='plus'>新增</Button>,
						// <Button key={2} onClick={this.allStart} type="primary" icon='line'>删除</Button>,
						// // <Button key={3} onClick={this.allStop} type="primary" icon='printer'>打印</Button>,
						// <Button key={4} onClick={this.derive} type="primary" icon='download'>导出模板</Button>,
						// <Button key={6} onClick={this.derive2} type="primary" icon='download'>导出选中</Button>,
						// <Upload {...propss} key={5}>
						// 	<Button type="primary">
						// 		<Icon type="upload" /> 导入
						// 	</Button>
						// </Upload>,
					]}
				>
					<TableCustomize
						rowSelection={rowSelection}
						columns={this.state.columns}
						rowKey={(record) => record.id}
						dataSource={dataSource}
						pagination={false}
						loading={loading}
						allowDrafting={true}
						// allowEditable={this.loadData}
						scroll={{ x: true, y: 500 }}
						rowClassName={(record, index) => {
							return (['editable-row', index % 2 === 0 ? 'editable-row' : 'editable-row12'])
						}}
					/>
					<BasicPagination pageNum={paging.pageNum} pageSize={paging.pageSize} total={paging.total} loadData={this.fetch} />
				</BasicLayout>
				<Drawer width={500} visible={drawerVisible} title={drawerTitle} onClose={this.handleCancel}>
					<AddForm
						compile={this.state.compile || null}
						returnModel={this.state.returnModel}
						formData={formData}
						onOk={this.onHandleOk}
						one={this.state.one}
						ref={node => (this.formDrawer = node)}
						onClose={this.handleCancel}
					/>
					<div
						style={{
							position: 'absolute',
							right: 0,
							bottom: 0,
							width: '100%',
							borderTop: '1px solid #e9e9e9',
							padding: '10px 16px',
							background: '#fff',
							textAlign: 'right',
						}}
					>
						<Button onClick={this.handleCancel} style={{ marginRight: 10 }}>{'取消'}</Button>
						<Button type="primary" onClick={this.onHandleOk} loading={buttonLoading}>
							{'确认'}
						</Button>
					</div>
				</Drawer>
				{/* 打印 */}
				<div id="prints" style={{ display: 'none' }}>
					<div style={{ textAlign: 'center', margin: '10px 0' }}>
						<Row style={{ fontSize: 20, fontWeight: 700 }}>{'质检表单'}</Row>
					</div>
					<TableCustomize
						columns={columns1}
						rowKey={(record) => record.id}
						dataSource={
							some === 0 || some === null ? dataSource : selectedRows}
						pagination={false}
						scroll={{ x: false }}
					/>
					<div style={{ width: '100%', textAlign: 'center', marginTop: '20px' }}>
						<Row style={{}}>第{1}页,共{1}页</Row>
					</div>
				</div>
			</div>
		);
	}
}